/*
   Copyright 2009 the original author or authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package com.googlecode.kohmori.springmvc;

import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.validation.BindException;

import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.googlecode.kohmori.reportgen.JDBCConnObj;

public class LoginFormController extends SimpleFormController
{
    
    private JDBCConnObj jdbcConnObj;    
    
    @Override
    protected Object formBackingObject(HttpServletRequest arg0) throws Exception {
        LoginReportParams form = (LoginReportParams) super.formBackingObject(arg0);
        form.setUsername("abc");
        form.setPassword("abc");
        form.setDatabaseName("toursdb");
        return form;        
    }

    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse arg1,
			Object object, BindException arg3) throws Exception {

        String desiredReport = request.getParameter("report");

        // desiredReport has already been validated via the 
        // RequestParameterHandlerMapping in the web context config file
        // to ensure it is pointing to a valid report
        RedirectView rdv = new RedirectView(desiredReport + ".pdf");
        
        ModelAndView mAv = new ModelAndView(rdv);
        
        // This is for reports that have sub report types
        // It copies the reportType parameter from login to parameter page
        // for subsequent usage during report generation.
        if (request.getParameter("reportType") != null) {
            mAv.addObject("reportType", request.getParameter("reportType"));
        }
      	return mAv;
    }

    /**
     * Trim whitespace from input fields.
     */
    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }   

    @Override
    protected void onBindAndValidate(HttpServletRequest request, Object object,
        BindException errors) throws Exception
    {
        if (!errors.hasErrors()) {
            HttpSession session = request.getSession(true);
            
            LoginReportParams form = (LoginReportParams) object;
            
            if (jdbcConnObj == null) {
               throw new IllegalStateException("(Internal error) Database " +
                       "connection is not set!");
            }
            
            try {
                jdbcConnObj.connectToDatabase(form.getUsername(), form.getPassword(),
                        form.getDatabaseName());
                session.setAttribute("connection", jdbcConnObj.getDBConn());
            } catch (IllegalStateException ex) {
                // "xxxxx" is to force use of fallback message (third argument)
                errors.rejectValue("username", "xxxxx", ex.getMessage());
            }
        }
    }

    /**
     * Setter for property jdbcConnObj.
     * @param jdbcConnObj New value of property jdbcConnObj.
     */
    public void setJdbcConnObj(JDBCConnObj jdbcConnObj) {
        this.jdbcConnObj = jdbcConnObj;
    }
}
